//
//  L_SMSCode_ActivateVC.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/4.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD

class L_SMSCode_ActivateVC: L_BaseViewController,NTESVerifyCodeManagerDelegate {
    var manager = NTESVerifyCodeManager.getInstance()
    
//    let PHONE_NUM = "PHONE_NUM"
    var smsVerifyCredential = ""
    
    let loginIdTextField = TextField()
    let passwdTextField = TextField()
    var actionBtn = Button()
    let timerBtn = Button()
    let tipsLab = UILabel()

    var timeCount = 60
    var timer : Timer?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

    //获取短信验证码
    /*neVaildeTicket    string 必须 网易NE的账号（captchaId）*/
    /*neVaildeCode    string 必须  网易NE返回的验证码（validate）*/
    func getSmsCode(neVaildeTicket:String, neVaildeCode:String) {
        let params :[String:Any] = ["mobile":loginIdTextField.text!,
                                    "neVaildeTicket":neVaildeTicket,
                                    "neVaildeCode":neVaildeCode]
        MBProgressHUD.showOrIncrease()
        API.request(url: .L_SMSCode_Activate, params: params) { (result) in
            if result.success {
               MBProgressHUD.hideOrDecrease()
                if (result.data?.getDictionary("data")) != nil {
                  self.smsVerifyCredential = result.data?.getDictionary("data")?.getString("smsVerifyCredential") ?? ""
                    self.codeTimer()
                }
            }else{
                MBProgressHUD.hideOrDecrease()
                let popup = PopupSureBox(title: result.errMsg ?? "激活失败，请核对并正确填写信息", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
            }
        }
    }
    
    func timerinvalidate() {
        timer?.invalidate()
        timer = nil
        print("\(self)已销毁")
    }
}

// MARK:- setupUI
extension L_SMSCode_ActivateVC {
    @objc override func setupUI() {
        self.view.backgroundColor = .white
        //头部图
        safeView.drawImage(imageView:headView, named: nil) { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview()
        }
        //底部图
        safeView.drawImage(imageView:footView, named: nil) { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        let titleBar = drawRoundCornerView(topOffset: 100)
        titleBar.drawLabel(text: "账户激活", fontSize: 23, fontWeight: .medium, textColor: .x333333) { (make) in
            make.left.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        
        //登录控件区域
        let loginIdView = drawImgLineView(topOffset: 80,img: nil).result
        //登录控件
        drawTextFieldInRoundCornerView(textField: loginIdTextField, placeHolder: "请输入手机号", roundCornerView: loginIdView,leftOffset: 5)
        loginIdTextField.keyboardType = .phonePad
        
        //验证密码控件区域
        let passwdView = drawImgLineView(topOffset: 28,img: nil).result
        //密码控件
        drawTextFieldInRoundCornerView(textField: passwdTextField, placeHolder: "请输入验证码", roundCornerView: passwdView,leftOffset: 5)
        passwdTextField.addTarget(self, action: #selector(psdfieldDidChanged(tf:)), for: UIControl.Event.editingChanged)
        passwdTextField.keyboardType = .numberPad
        passwdTextField.isSecureTextEntry = false
        
        passwdView.drawButton(button: timerBtn,title: "获取验证码", titleColor: .x999999, fontSize: 11) { (make) in
            make.right.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        timerBtn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
        timerBtn.addTarget(self, action: #selector(onTimerButtonClick(button:)), for: .touchUpInside)
        
        passwdView.drawLabel(label: tipsLab, text: "", fontSize: 10, textColor: .red){ (make) in
            make.top.equalTo(passwdTextField.snp.bottom).offset(7)
            make.left.equalTo(passwdTextField.snp.left)
        }
        
        let backbtn = safeView.drawButton(imageNamed: "L_Back") { (make) in
            make.top.equalToSuperview().offset(25)
            make.left.equalTo(titleBar.snp.left)
        }
        backbtn.hitEdgInsets = .init(top: -40, left: -40, bottom: -40, right: -40)
        backbtn.addTarget(self, action: #selector(onBackCheckClicked(button:)), for: .touchUpInside)
        
        //提交登录按钮
        actionBtn = drawRoundCornerButton(title:"下一步", topOffset: 71)
        actionBtn.addTarget(self, action: #selector(onSubmitButtonClick(button:)), for: .touchUpInside)

        if loginIdTextField.text?.count ?? 0 > 0, passwdTextField.text?.count ?? 0 > 0 {
            actionBtn.isSelected = false
        }
        else {
            actionBtn.isSelected = true
        }
        
        initKeyboardObserver()
        fillAccessoryToolBar()
    }
    
    func codeTimer() {
        if timer != nil {
            return
        }
        timer=Timer.scheduledTimer(timeInterval:1, target:self, selector:#selector(functickDown), userInfo:nil, repeats:true)
        //开始计时器
        timeCount = 60
        timer?.fire()
    }
}

// MARK:- 事件监听
extension L_SMSCode_ActivateVC {
    @objc func functickDown(){
        print("0timeCount\(timeCount)")
        if timeCount > 0 {
            timerBtn.isEnabled = false
            timerBtn.setTitleAndColor(title: "重新发送(\(String(describing: timeCount)))", color: .x999999)
            timeCount-=1
        }
        else {
            //消除计时器（页面释放是必须调用这个方法，不让会让页面和定时器不会释放）
            timerBtn.isEnabled = true
            timerBtn.setTitleAndColor(title: "重新发送", color: .x999999)
            timerinvalidate()
        }
    }
    
    @objc func onTimerButtonClick(button:UIButton){
        UIApplication.shared.keyWindow?.endEditing(true)
        codeAction()
    }
    
    @objc func onBackCheckClicked(button:UIButton){
        timerinvalidate()
        popViewController()
    }
    
    @objc func onSubmitButtonClick(button:UIButton){
        if loginIdTextField.text?.count ?? 0 > 0, passwdTextField.text?.count ?? 0 > 0 {
        }
        else {
            let popup = PopupSureBox(title: "请填写手机号和验证码", sureText: "确定")
            popup.show(vc: UIViewController.topMostController() ?? self)
            popup.onSureButtonClick = {
                //确定执行
            }
            return
        }
        let vc = L_UserInfoVC(smsVerify: smsVerifyCredential, code: passwdTextField.text ?? "", mob: loginIdTextField.text ?? "")
        vc.getActivatedUser(callback: { (sec,_) in
            if sec {
                self.pushViewController(vc)
            }
        })
    }

    @objc func  psdfieldDidChanged(tf : UITextField) {
        if loginIdTextField.text?.count ?? 0 > 0, passwdTextField.text?.count ?? 0 > 0 {
            actionBtn.isSelected = false
        }
        else {
            actionBtn.isSelected = true
        }
    }
    
    func codeAction() {
                // 如果需要了解组件的执行情况,则实现回调
        manager?.delegate = self
                
                // captchaid的值是每个产品从后台生成的,比如 @"a05f036b70ab447b87cc788af9a60974"
                
                // 传统验证码
                let captchaid = CAPTCHA_ID
        manager?.mode = .normal
                
                // 无感知验证码
        //        NSString *captchaid = @"6a5cab86b0eb4c309ccb61073c4ab672";
        //        self.manager.mode = NTESVerifyCodeBind;
                
        manager?.configureVerifyCode(captchaid, timeout: 7.0)
                
                // 设置语言
        manager?.lang = .CN
                
                // 设置透明度
        manager?.alpha = 0.3
                
                // 设置颜色
        manager?.color = UIColor.black
                
                // 设置frame
        manager?.frame = CGRect.null
                
                // 是否开启降级方案
        manager?.openFallBack = true
        manager?.fallBackCount = 3
                
                // 显示验证码
        manager?.openVerifyCodeView()
        tipsLab.text = nil
    }

    /**
     * 验证码组件初始化完成
     */
    
    func verifyCodeInitFinish() {
        print("收到初始化完成的回调")
    }
    
    /**
    * 验证码组件初始化出错
    *
    * @param message 错误信息
    */
    func verifyCodeInitFailed(_ error: [Any]!) {
        print("收到错误信息的回调")
    }
    
    /**
    * 完成验证之后的回调
    *
    * @param result 验证结果 BOOL:YES/NO
    * @param validate 二次校验数据，如果验证结果为false，validate返回空
    * @param message 结果描述信息
    *
    */
    func verifyCodeValidateFinish(_ result: Bool, validate: String!, message: String!) {
        if result {
            print("完成验证之后的回调")
            print(validate ?? "validate失败")
            print(message ?? "message失败")
            if loginIdTextField.text?.validateMobile() ?? false {
                getSmsCode(neVaildeTicket: CAPTCHA_ID, neVaildeCode: validate)
                self.codeTimer()
            }
            else {
                tipsLab.text = "手机号码不规范，请重新输入"
            }
        }
    }
    

    /**
     * 关闭验证码窗口后的回调
     */
    func verifyCodeCloseWindow() {
        print("关闭验证码窗口后的回调")
        
    }
    
    /**
    * 网络错误
    *
    * @param error 网络错误信息
    */
    func verifyCodeNetError(_ error: Error!) {
        print("网络错误")
        
    }
}
